const Message = require('../models/message');

class MessageController {
  /**
   * 创建消息
   * @param {Koa.Context} ctx - Koa上下文
   */
  static async createMessage(ctx) {
    try {
      const { title, content, recipients, type } = ctx.request.body;
      const senderId = ctx.user?.id;
      
      const message = new Message({
        title,
        content,
        sender: senderId,
        recipients,
        type,
        status: 'pending'
      });
      
      await message.save();
      
      ctx.status = 201;
      ctx.body = {
        success: true,
        data: message,
        message: '消息创建成功'
      };
    } catch (error) {
      ctx.status = error.status || 400;
      ctx.body = {
        success: false,
        message: error.message || '消息创建失败'
      };
    }
  }

  /**
   * 获取消息列表
   * @param {Koa.Context} ctx - Koa上下文
   */
  static async getMessages(ctx) {
    try {
      const { page = 1, limit = 20, status, type } = ctx.query;
      const userId = ctx.user?.id;
      const role = ctx.user?.role;
      
      const query = {};
      
      // 根据用户角色过滤消息
      if (role === 'admin' || role === 'teacher') {
        // 管理员和老师可以查看所有消息
      } else {
        // 学生只能查看发送给他们的消息
        query.$or = [
          { recipients: userId },
          { recipients: 'all' }
        ];
      }
      
      // 添加状态过滤
      if (status) {
        query.status = status;
      }
      
      // 添加类型过滤
      if (type) {
        query.type = type;
      }
      
      const skip = (page - 1) * limit;
      const messages = await Message.find(query)
        .populate('sender', 'username name role')
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(parseInt(limit))
        .exec();
      
      const total = await Message.countDocuments(query);
      
      ctx.body = {
        success: true,
        data: {
          messages,
          pagination: {
            total,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(total / limit)
          }
        },
        message: '获取消息列表成功'
      };
    } catch (error) {
      ctx.status = error.status || 500;
      ctx.body = {
        success: false,
        message: error.message || '获取消息列表失败'
      };
    }
  }

  /**
   * 获取单个消息
   * @param {Koa.Context} ctx - Koa上下文
   */
  static async getMessageById(ctx) {
    try {
      const { id } = ctx.params;
      const userId = ctx.user?.id;
      const role = ctx.user?.role;
      
      const message = await Message.findById(id)
        .populate('sender', 'username name role')
        .exec();
      
      if (!message) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '消息不存在'
        };
        return;
      }
      
      // 检查权限：只有管理员、老师、发送者或接收者可以查看消息
      if (role !== 'admin' && role !== 'teacher' && 
          message.sender.toString() !== userId && 
          message.recipients !== 'all' && 
          !message.recipients.includes(userId)) {
        ctx.status = 403;
        ctx.body = {
          success: false,
          message: '无权查看此消息'
        };
        return;
      }
      
      // 如果是接收者且消息未读，更新为已读
      if (message.recipients !== 'all' && message.recipients.includes(userId)) {
        message.status = 'read';
        await message.save();
      }
      
      ctx.body = {
        success: true,
        data: message,
        message: '获取消息成功'
      };
    } catch (error) {
      ctx.status = error.status || 500;
      ctx.body = {
        success: false,
        message: error.message || '获取消息失败'
      };
    }
  }

  /**
   * 更新消息
   * @param {Koa.Context} ctx - Koa上下文
   */
  static async updateMessage(ctx) {
    try {
      const { id } = ctx.params;
      const updates = ctx.request.body;
      const userId = ctx.user?.id;
      const role = ctx.user?.role;
      
      const message = await Message.findById(id).exec();
      
      if (!message) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '消息不存在'
        };
        return;
      }
      
      // 检查权限：只有管理员、老师或发送者可以更新消息
      if (role !== 'admin' && role !== 'teacher' && message.sender.toString() !== userId) {
        ctx.status = 403;
        ctx.body = {
          success: false,
          message: '无权更新此消息'
        };
        return;
      }
      
      // 不允许更新的字段
      delete updates.sender;
      delete updates.createdAt;
      
      Object.assign(message, updates);
      await message.save();
      
      ctx.body = {
        success: true,
        data: message,
        message: '消息更新成功'
      };
    } catch (error) {
      ctx.status = error.status || 400;
      ctx.body = {
        success: false,
        message: error.message || '消息更新失败'
      };
    }
  }

  /**
   * 删除消息
   * @param {Koa.Context} ctx - Koa上下文
   */
  static async deleteMessage(ctx) {
    try {
      const { id } = ctx.params;
      const userId = ctx.user?.id;
      const role = ctx.user?.role;
      
      const message = await Message.findById(id).exec();
      
      if (!message) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '消息不存在'
        };
        return;
      }
      
      // 检查权限：只有管理员、老师或发送者可以删除消息
      if (role !== 'admin' && role !== 'teacher' && message.sender.toString() !== userId) {
        ctx.status = 403;
        ctx.body = {
          success: false,
          message: '无权删除此消息'
        };
        return;
      }
      
      await message.deleteOne();
      
      ctx.body = {
        success: true,
        message: '消息删除成功'
      };
    } catch (error) {
      ctx.status = error.status || 500;
      ctx.body = {
        success: false,
        message: error.message || '消息删除失败'
      };
    }
  }
}

module.exports = MessageController;